<style src="./index.scss" lang="scss" scoped></style>
<template>
    <main class="page-base-box" :class="{enter: pageEnter}" ref="pageBaseRef">
        <header class="page-base-header"
            :class="{ sticky: headerSticky === headerStickyValue}"
            ref="pageBaseHeaderRef" v-if="!noHeader">
            <slot name="header" v-bind:data="{ headerSticky }"></slot>
        </header>
        <section class="page-base-body">
            <slot></slot>
        </section>
        <footer class="page-base-footer" v-if="!noFooter">
            <slot name="footer"></slot>
        </footer>
    </main>
</template>

<script lang="ts">
import { Component, Prop, Vue, Ref, Emit } from "vue-property-decorator";
import { ObserverEvent, throttle } from "@/utils";
@Component
export default class PageBaseBox extends Vue {
    @Prop({
        type: Boolean,
        default: false
    }) readonly noHeader!: boolean;

    @Prop({
        type: Boolean,
        default: false
    }) readonly noFooter!: boolean;

    pageEnter = false;
    headerStickyValue = 60;
    headerSticky = 0;
    @Ref('pageBaseRef') readonly pageBaseRef!: HTMLButtonElement
    @Ref('pageBaseHeaderRef') readonly pageBaseHeaderRef!: HTMLButtonElement
    mounted() {
        setTimeout(() => {
            this.pageEnter = true;
            this.bindAndEmitScroll();
        }, 100);
    }

    @Emit("body-scroll") onBodyScroll(e: any) { return e; };

    bindAndEmitScroll() {
        const diff = this.headerStickyValue;
        let endChange = 0;
        const scrollEvent = ObserverEvent(this.pageBaseRef, "scroll", throttle((e: any) => {
            const { scrollTop } = e.target;
            const { clientHeight } = this.pageBaseHeaderRef;
            endChange = Math.max(clientHeight - scrollTop, diff);
            this.headerSticky = scrollTop === 0 ? scrollTop : endChange;
            this.onBodyScroll(e);
        }, 0));
        this.$on("hook:beforeDestroy", () => {
            scrollEvent.destroy();
        });
    }
}
</script>
